iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 65

[Day 63 ] Binary Tree Inorder Traversal (Easy)

  • 分享至 

  • xImage
  •  

94. Binary Tree Inorder Traversal

Solution 1: Recursive

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        def dfs(root, ans):
            if not root:
                return
            dfs(root.left, ans)
            ans.append(root.val)
            dfs(root.right, ans)
        ans = []
        dfs(root, ans)
        return ans

Time Complexity: O(N)
Space Complexity: O(N) // Recursive call stack

Solution 2: Iterative

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        ans = []
        stack = []
        while stack or root:
            if root:
                stack.append(root)
                root = root.left
            else:
                top = stack.pop()
                ans.append(top.val)
                root = top.right
        return ans

Time Complexity: O(N)
Space Complexity: O(N)

Reference

https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/31381/Python-recursive-and-iterative-solutions.


上一篇
[Day 62 ] Rotate Array (Medium)
下一篇
[Day 64 ] Merge Intervals (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言